//  IDVI 1.0 source copyright 1996 Garth A. Dickie
//
//  This source is free for non-commercial use.  No warranty, etc.
//  Please acknowledge reuse by including the line:
//
//  "Based in part on IDVI 1.0 source copyright 1996 Garth A. Dickie"
//
//  in your documentation and source code.  For commercial use or
//  distribution, please contact the author.  Please also send
//  questions, comments, bug reports, or fixes.
//
//  Best Regards,
//  Garth A. Dickie
//  dickie@elastic.avid.com

package ibook.v10.util;

//  DelayedCondition behaves like an ExclusiveCondition, but
//  the return from get( ) is delayed by the delay specified
//  at construction time (in milliseconds).

public class DelayedCondition extends Condition {
    final private static long   kFudgeFactor = 30;
    private boolean             state;
    private long                delay;
    private long                readyTime;

    public DelayedCondition( boolean state, long delay ) {
        this.state = state;
        this.delay = delay;
    }

    public DelayedCondition( long delay ) {
        this( waiting, delay );
    }

    public synchronized void clear( ) {
        state = waiting;
    }

    public synchronized void get( ) {
        Thread thread = Thread.currentThread( );

        while( state == waiting ) {
            try {
                wait( );
            } catch( InterruptedException e ) {
            }

            long remaining = readyTime - System.currentTimeMillis( );
            while( remaining > 0 ) {
                try {
                    thread.sleep( remaining + kFudgeFactor );
                } catch( InterruptedException e ) {
                }
                remaining = readyTime - System.currentTimeMillis( );
            }
        }

        state = waiting;
    }

    public synchronized void put( ) {
        state = ready;
        readyTime = System.currentTimeMillis( ) + delay;
        notify( );
    }
}
